<?php
namespace app\backstage\logic;
use think\Db;
class Withdrawal
{
    /*
     * 代理提现汇总
     * */
    public function getAgentSummaryList($params)
    {
        $field = 'id,account,remarks,parent_id';

        $params['role_id'] = 5;
        $withdrawalWhere = $summaryAgentWhere = [];
        if(isset($params['end_date']) && strlen($params['end_date']) > 0)
        {
            list($startDate, $endDate) = explode(' ~ ', $params['end_date']);
            $withdrawalWhere[] = ['settlement_date', '>=', $startDate];
            $withdrawalWhere[] = ['settlement_date', '<=', $endDate];
            $summaryAgentWhere[] = ['report_date', '>=', $startDate];
            $summaryAgentWhere[] = ['report_date', '<=', $endDate];
        }

        $condition[] = ['parent_id', 'eq', 'gt:0','eb_id'];
        $condition[] = ['id', 'eq', 'gt:0','agent_id'];
        $condition[] = ['role_id', 'eq', 'gt:0','role_id'];

        $where   = buildQueryCondition($condition, $params);

        if( isset($params['field']) ){
            $orderBy = [ $params['field'] => $params['order'] ];
        }else{
            $orderBy = ['id' => 'DESC'];
        }

        $Account = \think\facade\App::model('Account');
        $list = $Account->getList($where, $field, $params['page'], $params['limit'], $orderBy);

        if($params['page'] == 1 )
        {
            if( !(isset($params['agent_id']) && $params['agent_id'] > 0) && !(isset($params['eb_id']) && $params['eb_id'] > 0))
            {
                $list[] = ['id'=>0,'account'=>'平台所属','remarks'=>'未归属代理'];
            }

        }

        if ($list) {

            foreach ($list as $k => $v) {

                $recharge_amount = Db::table('rp_income_summary_daily_agent')->where('agent_id',$v['id'])->where($summaryAgentWhere)->sum('recharge_amount');
                $commission_amount = Db::table('rp_income_summary_daily_agent')->where('agent_id',$v['id'])->where($summaryAgentWhere)->sum('commission_amount');
                $wp_amount = Db::table('cms_withdrawal_record')->where('agent_id',$v['id'])->where('status',2)->where($withdrawalWhere)->sum('money');
                $paid_amount = Db::table('cms_withdrawal_record')->where('agent_id',$v['id'])->where('status',3)->where($withdrawalWhere)->sum('money');

                $ud_amount          = $commission_amount - ($paid_amount+$wp_amount);
                $recharge_amount    = getQuotient($recharge_amount,100);
                $commission_amount  = getQuotient($commission_amount,100);
                $wp_amount          = getQuotient($wp_amount,100);
                $paid_amount        = getQuotient($paid_amount,100);
                $ud_amount          = getQuotient($ud_amount,100);

                $settlement_date = Db::table('cms_withdrawal_record')->where('agent_id',$v['id'])->where($withdrawalWhere)->order('id DESC')->value('settlement_date');
                $list[$k]['eb_name']            = isset($v['parent_id']) && $v['parent_id'] > 0 ? Db::table("cms_manager_user")->where("id",$v['parent_id'])->value("account") : '';
                $list[$k]['agent_name']         = strlen($v['remarks']) > 1 ? $v['account'].'（'.$v['remarks'].'）' : $v['account'];
                $list[$k]['recharge_amount']    = $recharge_amount;
                $list[$k]['commission_amount']  = $commission_amount;
                $list[$k]['wp_amount']          = $wp_amount;
                $list[$k]['paid_amount']        = $paid_amount;
                $list[$k]['ud_amount']          = $ud_amount;
                $list[$k]['settlement_date']    = $settlement_date;
            }
        }

        $result['count'] = $Account->getTotalNumber($where);
        $result['list'] = $list;
        return $result;
    }

    /*列表数据*/
    public function getList($params)
    {
        $field = 'id,agent_id,bank_id,money,received_money,status,settlement_date,create_time';

        if (request()->_role->alias == 'agent') {
            $params['agent_id'] = request()->_user->id;
        }

        $condition[] = ['agent_id', 'eq', 'gt:0','agent_id'];
        $condition[] = ['status', 'eq', 'gt:0','status'];
        $condition[] = ['create_date', 'egt', 'require','start_date'];
        $condition[] = ['create_date', 'elt', 'require','end_date'];

        $where   = buildQueryCondition($condition, $params);

        if( isset($params['field']) ){
            $orderBy = [ $params['field'] => $params['order'] ];
        }else{
            $orderBy = ['id' => 'DESC'];
        }

        $Withdrawal = \think\facade\App::model('Withdrawal');
        $list = $Withdrawal->getList($where, $field, $params['page'], $params['limit'], $orderBy);

        if ($list) {

            $state = [  '1' => '<span class="layui-badge layui-bg-red">待审核</span>',
                '2' => '<span class="layui-badge layui-bg-blue">已审未打款</span>',
                '3' => '<span class="layui-badge layui-bg-cyan">已打款</span>'
            ];

            $agent_id_gh = array_unique(array_column($list, 'agent_id'));
            $agents = Db::table('cms_manager_user')->where('id', 'in', $agent_id_gh)->column('id,account');

            foreach ($list as $k => $v) {
                $list[$k]['state']      = $state[$v['status']];
                $list[$k]['agent_name'] = isset($agents[$v['agent_id']]) ? $agents[$v['agent_id']]."（{$v['agent_id']}）" : '';
                $list[$k]['money']      = getQuotient($v['money'],100);
            }
        }

        $result['count'] = $Withdrawal->getTotalNumber($where);
        $result['list'] = $list;
        return $result;
    }

    /*数据获取*/
    public function getInfo($where)
    {
        $field = 'id,agent_id,bank_id,money,received_money,status,create_time';
        $Withdrawal = \think\facade\App::model('Withdrawal');

        $info = $Withdrawal->getOne($where,$field);

        if($info)
        {
            $info['money'] = round($info['money']/100,2);

            $agentInfo = Db::table('cms_manager_user')->where('id',$info['agent_id'])->field('account')->findOrEmpty();
            $info['agent_name'] = $agentInfo ? $agentInfo['account'] : '';

            $field = 'bank_name,branch_title,payee_name,bank_account,contact_person,tel,status';
            $Bank = \think\facade\App::model('Bank');

            $where_b[] = ['id','=',$info['bank_id']];
            $bankInfo = $Bank->getOne($where_b,$field);
            $info = array_merge($info,$bankInfo);
        }

        return $info;
    }

    /*
     * 审核
     * */
    public function examineInfo($params)
    {
        $withdrawal_amount = getByWithdrawalAmountAgent($params['agent_id']);
        $commission_amount = getByCommissionAmountAgent($params['agent_id']);

        if($withdrawal_amount > $commission_amount)
        {
            return ['code'=>102,'msg'=>'提现总金额大于该代理商分成总金额，请联系管理员核实异常'];
        }

        $where[] = ['id','=',$params['id']];

        $Withdrawal = \think\facade\App::model('Withdrawal');

        $record = $Withdrawal->getOne($where,'id,status');
        if($record['status'] != 1)
        {
            return ['code'=>102,'msg'=>'该提现记录已处理，请勿重复操作'];
        }

        $res = $Withdrawal->updateRecord($where,['status'=>2]);

        if($res){
            return ['code'=>100,'msg'=>'操作成功'];
        }

        return ['code'=>102,'msg'=>'操作失败'];
    }

    /*确认打款*/
    public function confirmPayment($params)
    {
        $where[] = ['id','=',$params['id']];
        $Withdrawal = \think\facade\App::model('Withdrawal');

        $record = $Withdrawal->getOne($where,'id,status');
        if($record['status'] != 2)
        {
            return ['code'=>102,'msg'=>'该提现记录已处理，请勿重复操作'];
        }

        $res = $Withdrawal->updateRecord($where,['status'=>3]);

        if($res){
            return ['code'=>100,'msg'=>'操作成功'];
        }

        return ['code'=>102,'msg'=>'操作失败'];
    }

    /*申请提现*/
    public function addInfo($params)
    {
        $date = date('Y-m-d');
        $count = Db::table('cms_withdrawal_record')->where('agent_id',request()->_user->id)
                ->where('create_date',$date)->count();

        if($count >= 10){
            return ['code'=>102,'msg'=>'今日提现次数已超10次，请改日提现'];
        }

        $record = Db::table('cms_bank_card')->where('agent_id',request()->_user->id)
                ->where('status',2)->order('id DESC')->findOrEmpty();

        $balance = Db::table('rp_income_summary_daily_agent')
            ->where('report_date','<=',$params['settlement_date'])
            ->where('status','=',1)
            ->where('agent_id','=',request()->_user->id)->sum('commission_amount');

        if($balance < 1)
        {
            return ['code'=>102,'msg'=>'提现金额大于账户当前可提现余额'];
        }

        $money = intval($params['money']*100);
        $balance = intval($balance);

        if($money > $balance)
        {
            return ['code'=>102,'msg'=>'提现金额大于账户当前可提现余额'];
        }

        $data['agent_id']       = request()->_user->id;
        $data['money']          = $balance;
        $data['create_date']    = $date;
        $data['bank_id']        = $record['id'];
        $data['settlement_date'] = $params['settlement_date'];

        $Withdrawal = \think\facade\App::model('Withdrawal');
        $res = $Withdrawal->insertRecord($data);

        if($res){

            Db::table('rp_income_summary_daily_agent')
                ->where('report_date','<=',$params['settlement_date'])
                ->where('status','=',1)
                ->where('agent_id','=',request()->_user->id)->update(['status'=>2]);

            return ['code'=>100,'msg'=>'操作成功'];
        }

        return ['code'=>102,'msg'=>'操作失败'];
    }

}